package com.qianjiangcloud.store.activity.account;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.ScrollView;
import android.widget.TextView;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;


public class MyScoreFragment extends BaseDoFragment {

	private ListView mListView;
	private RadioButton mRuleRadioButton , mHistoryRadioButton;
	private LinearLayout mHeaderView;
	private ArrayList<JSONObject> listHistory = new ArrayList<JSONObject>();
	private HistoryAdapter mAdapter;
	private TextView mYingBangTxt;
	private int mPageNum=0;
	private boolean isLoadEnd;
	private boolean isLoaddingData;
//	private String mContent;
	private WebView mWebView;
	private ScrollView mScrollView=null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setShowTitleBar(false);
	}
	
	@Override
	public void init(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_shang_bang, null);


		mScrollView= (ScrollView) rootView.findViewById(R.id.mscroll);
		((TextView)findViewById(R.id.fragment_my_yingbang_titlebar_title)).setText("我的积分");
		mListView = (ListView) rootView.findViewById(R.id.fragment_my_yingbang_list);
		mRuleRadioButton = (RadioButton) rootView.findViewById(R.id.fragment_my_yingbang_rule);
		mHistoryRadioButton = (RadioButton) rootView.findViewById(R.id.fragment_my_yingbang_history);
		mWebView=(WebView) rootView.findViewById(R.id.rule_webView);
		((RadioGroup)rootView.findViewById(R.id.goods_detail_action_radios)).setOnCheckedChangeListener(checkedChangeListener);
//		mRuleRadioButton.setChecked(true);
//		mRuleRadioButton.setOnCheckedChangeListener(checkedChangeListener);
//		mHistoryRadioButton.setOnCheckedChangeListener(checkedChangeListener);
		mHeaderView = (LinearLayout) rootView.findViewById(R.id.fragment_my_yingbang_layout);
		mYingBangTxt = (TextView) mHeaderView.findViewById(R.id.fragment_my_yingbang);
//		Run.removeFromSuperView(mHeaderView);
//		mHeaderView.setLayoutParams(new AbsListView.LayoutParams(mHeaderView.getLayoutParams()));
//		mListView.addHeaderView(mHeaderView);
		mAdapter = new HistoryAdapter();
		mListView.setAdapter(mAdapter);
		mYingBangTxt.setText(getCoinString("0"));
		findViewById(R.id.fragment_my_yingbang_back).setOnClickListener(this);
		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
								 int visibleItemCount, int totalItemCount) {
				if (mHistoryRadioButton.isChecked()) {
					if ((totalItemCount - (firstVisibleItem + visibleItemCount) == 0) && !isLoadEnd && !isLoaddingData) {
						loadNextPage(mPageNum);
					}
				}
			}
		});
		findViewById(R.id.fragment_my_yingbang_layout).setVisibility(View.VISIBLE);
//		mWebView.loadUrl(Constant.DOMAIN+"/wap/statics-point.html");
		mListView.setVisibility(View.VISIBLE);
		mWebView.setVisibility(View.GONE);
		Run.excuteJsonTask(new JsonTask(), new GetArticleDetail());
		//loadNextPage(0);
	}
	
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.fragment_my_yingbang_back) {
			mActivity.finish();
		} else {
			super.onClick(v);
		}
	}
	
	private SpannableString getCoinString(String coin){
		String str = "我目前拥有"+coin+"积分";
		SpannableString sp = new SpannableString(str);
		AbsoluteSizeSpan spanSize = new AbsoluteSizeSpan(Run.sp2px(mActivity, 60));
		sp.setSpan(spanSize, 5, 5 + coin.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		return sp;
	} 
	
	private OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {

			if(null!=mScrollView) {
				mScrollView.smoothScrollTo(0, 0);
			}

			if(checkedId==R.id.fragment_my_yingbang_rule){
				mWebView.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
//				listHistory.clear();
			}else if(checkedId==R.id.fragment_my_yingbang_history){
				mWebView.setVisibility(View.GONE);
				mListView.setVisibility(View.VISIBLE);
//				loadNextPage(0);
			}
			mAdapter.notifyDataSetChanged();
		}
		
	};
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onPause() {
		super.onPause();
	}
	
	private void loadNextPage(int page){
		if (isLoaddingData || isLoadEnd ) {
			return;
		}
		this.mPageNum = page + 1;
		if (this.mPageNum == 1) {
			listHistory.clear();
			mAdapter.notifyDataSetChanged();
		}
		new JsonTask().execute(new GetHistoryTask());
	}
	
	private class GetHistoryTask implements JsonTaskHandler{

		@Override
		public void task_response(String json_str) {
			isLoaddingData = false;
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject data = all.optJSONObject("data");
					if (data != null) {
						if(data.optInt("page") <= mPageNum){
							isLoadEnd = true;
						}
						mYingBangTxt.setText(getCoinString(data.optString("total" , "0")));
						JSONArray list = data.optJSONArray("historys");
						int count = list == null? 0 : list.length();
						for (int i = 0; i < count; i++) {
							listHistory.add(list.getJSONObject(i));
						}
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
				mAdapter.notifyDataSetChanged();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			isLoaddingData = true;
			JsonRequestBean req = new JsonRequestBean( "mobileapi.point.point_detail");
			req.addParams("n_page", String.valueOf(mPageNum));
			return req;
		}
		
	}
	
	private class HistoryAdapter extends BaseAdapter{
		
		private JSONObject obj; 

		@Override
		public int getCount() {
			return listHistory.size();
//			return 10;
		}

		@Override
		public JSONObject getItem(int position) {
			return listHistory.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder ;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(mActivity).inflate(R.layout.item_yingbang_history, null);
				holder.count = (TextView) convertView.findViewById(R.id.item_yingbang_history_coin);
				holder.desc = (TextView) convertView.findViewById(R.id.item_yingbang_history_desc);
				holder.date = (TextView) convertView.findViewById(R.id.item_yingbang_history_date);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			obj = getItem(position);
			if (obj != null) {
				int change_point = obj.optInt("change_point");
				if (change_point >= 0) {
					holder.count.setText(Run.buildString("+",change_point,"积分"));
				} else {
					holder.count.setText(Run.buildString("",change_point,"积分"));
				}
				holder.desc.setText(obj.optString("reason"));
				holder.date.setText(getFormatTime(obj.optLong("addtime")));
			}
			return convertView;
		}

		private String getFormatTime(long time){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(time * 1000L);
			return sdf.format(c.getTime());
		}
		
	}
	
	private class ViewHolder{
		private TextView count;
		private TextView date;
		private TextView desc;
	}
	
	private class GetArticleDetail implements JsonTaskHandler{

		@Override
		public void task_response(String json_str) {
			try {
				hideLoadingDialog_mt();
				findViewById(R.id.fragment_my_yingbang_layout).setVisibility(View.VISIBLE);
				JSONObject all = new JSONObject(json_str);
				if(Run.checkRequestJson(mActivity, all)){
					JSONObject data = all.getJSONObject("data");
					JSONObject body = data.getJSONObject("bodys");
					String nContent = body.optString("content");
//					mContent = "<div style=\"background-color: rgb(255, 255, 255); padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; cursor: text; width: 100%; height: 100%; overflow-x: auto; overflow-y: auto; font-family: Arial, Verdana, sans-serif; font-size: 12px; \"><div class=\"pageWrap\"><h2>体贴的售后服务<\/h2>本网站所售产品均实行三包政策，请顾客保存好有效凭证，以确保我们为您更好服务。本公司的客户除享受国家规定“三包”。您可以更放心地在这里购物。<br\/><h3>保修细则<\/h3><h4>一、在本网站购买的商品，自购买日起(以到货登记为准)7日内出现性能故障，您可以选择退货、换货或修理。<\/h4><ol>\n\t<li>在接到您的产品后，我公司将问题商品送厂商特约维修中心检测；<\/li>\n\t<li>检测报出来后，如非人为损坏的，是产品本身质量问题，我公司会及时按您的要求予以退款、换可或维修。<\/li>\n\t<li>如果检测结果是无故障或是人为因素造成的故障，我公司会及时通知您，并咨询您的处理意见。<\/li>\n<\/ol>\n<h4>二、在本公司购买的商品，自购日起(以到货登记为准)15日内出现性能故障，您可以选择换货或修理。(享受15天退换货无需理由的商品，按《15天退换货无需理由细则》办理)<\/h4><ol>\n\t<li>在接到您的产品后，我公司将问题商品送厂商特约维修中心检测；<\/li>\n\t<li>检测报出来后，如非人为损坏的，是产品本身质量问题，我公司会及时按您的要求予以退款、换可或维修。<\/li>\n\t<li>如果检测结果是无故障或是人为因素造成的故障，我公司会及时通知您，并咨询您的处理意见。<\/li>\n<\/ol>\n<h4>三、在本公司购买的商品，自购日起(以到货登记为准)一年之内出现非人为损坏的质量问题，本公司承诺免费保修。<\/h4><ol>\n\t<li>在接到您的产品后，我公司将问题商品送厂商特约维修中心检测；<\/li>\n\t<li>检测报出来后，如非人为损坏的，是产品本身质量问题，我公司会及时按您的要求予以退款、换可或维修。<\/li>\n\t<li>如果检测结果是无故障或是人为因素造成的故障，我公司会及时通知您，并咨询您的处理意见。<\/li>\n<\/ol>\n<h3>收费维修：<\/h3><h4>一、对于人为造成的故障，本公司将采取收费维修，包括：<\/h4><ol>\n\t<li>产品内部被私自拆开或其中任何部分被更替；<\/li>\n\t<li>商品里面的条码不清楚，无法成功判断；<\/li>\n\t<li>有入水、碎裂、损毁或有腐蚀等现象；<\/li>\n\t<li>过了保修期的商品。<\/li>\n<\/ol>\n<h4>二、符合以下条件，可以要求换货：<\/h4><ol>\n\t<li>客户在收到货物时当面在送货员面前拆包检查，发现货物有质量问题的<\/li>\n\t<li>实际收到货物与网站上描述的有很大的出入的<\/li>\n\t<li>换货流程：客户当面要求送货人员退回货物，然后与我们联系。我们会在一个工作日内为您重新发货，货物到达时间顺延。<\/li>\n<\/ol>\n<h4>三、符合以下条件，可以要求退货：<\/h4>客户收到货物后两天之内，<ol>\n\t<li>发现商品有明显的制造缺陷的<\/li>\n\t<li>货物经过一次换货但仍然存在质量问题的<\/li>\n\t<li>由于人为原因造成超过我们承诺到货之日三天还没收到货物的<\/li>\n<\/ol>\n退货流程：客户在收到货物后两天内与我们联系，我们会在两个工作日内通过银行汇款把您的货款退回。<h4>在以下情况我们有权拒绝客户的退换货要求：<\/h4><ol>\n\t<li>货物出现破损，但没有在收货时当场要求送货人员换货的<\/li>\n\t<li>超过退换货期限的退换货要求<\/li>\n\t<li>退换货物不全或者外观受损<\/li>\n\t<li>客户发货单据丢失或者不全<\/li>\n\t<li>产品并非我们提供<\/li>\n\t<li>货物本身不存在质量问题的<\/li>\n<\/ol>\n<\/div><\/div>"; 
					mWebView.setBackgroundColor(0x00000000);
//					mWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
					mWebView.loadDataWithBaseURL(null, nContent, "text/html", "UTF-8", null);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			JsonRequestBean req = new JsonRequestBean( "mobileapi.info.score_rule");
//			req.addParams("article_id", "61");
			return req;
		}
	}
}
